#include "head.h"

//上传文件
int putsFunc(int sockfd,const char * filename){
    /*if(access(filename,F_OK)!=0){
        printf("文件不存在\n");
        return -1;
    }*/
    int iferror;
    recv(sockfd,&iferror,sizeof(int),0);
    if(iferror==-1){
        printf("puts is error\n");
        return -1;
    }
    train_t train_file;
    bzero(&train_file,sizeof(train_file));
    //计算md5值，传给服务器
    char MD5[128]={0};
    getFileMD5(filename,MD5);
    strcpy(train_file.data,MD5);
    train_file.length=strlen(MD5);
    send(sockfd,&train_file,sizeof(train_file.length)+train_file.length,MSG_NOSIGNAL);

    printf("开始上传......\n");

    recvn(sockfd,&iferror,sizeof(int));
    if(iferror==-2){
        printf("有同名文件\n");
        return -1;
    }//-2代表有同名文件
    int ret=0;
    recvn(sockfd,&ret,sizeof(ret));
    if(ret==-111){
        printf("秒传完成\n");
        return 0;
    }

    int fd=open(filename,O_RDWR);
    struct stat statbuf;
    fstat(fd,&statbuf);
    int cursize=0;
    int totalsize=statbuf.st_size;
    while(1){
        bzero(&train_file,sizeof(train_file));
        ssize_t sret=read(fd,train_file.data,sizeof(train_file.data));
        cursize+=sret;
        printf("%d%%\n",(cursize)*100/totalsize);
        if(sret==0){
            printf("上传结束\n");
            break;
        }

        train_file.length=sret;
        sret=send(sockfd,&train_file,sizeof(train_file.length)+train_file.length,MSG_NOSIGNAL);

    }
    train_file.length=0;
    send(sockfd,&train_file,sizeof(train_file.length),MSG_NOSIGNAL);

    close(fd);
    return 0;
}
